package com.ydgg.ltar.wechat;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

public class WeChatApi {

	/**
	 * 微信消息接收和token验证
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/ownerCheck")
	public void ownerCheck(Model model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		System.out.println(111);
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		PrintWriter print;
		if (isGet) {
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 随机字符串
			String echostr = request.getParameter("echostr");
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (signature != null
					&& CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
				try {
					print = response.getWriter();
					print.write(echostr);
					print.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@RequestMapping("/loginByWeiXin")
	public String loginByWeiXin(HttpServletRequest request,
			Map<String, Object> map) {
		// 微信接口自带 2 个参数
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		System.out.println("code = " + code + ", state = " + state);

		if (code != null && !"".equals(code)) {
			// 授权成功, 微信获取用户openID
			OAuthInfo authInfo = WeiXinUtil.getAccess_token(code);
			String openid = authInfo.getOpenid();
			String access_token = authInfo.getAccess_token();

			if (access_token == null) {
				// Code 使用过 异常
				System.out.println("Code 使用过 异常.....");
				return "redirect:" + WeiXinUtil.getStartURLToGetCode();
			}

//			// 数据库中查询微信号是否绑定平台账号
//			SysUser sysUser = weiXinService.getUserByWeiXinID(openid);
//			if (sysUser == null) {
//				String randomStr = StringUtils.getRandomString(50);
//				request.getSession().setAttribute(openid, randomStr);
//				// 尚未绑定账号
//				System.out.println("尚未绑定账号.....");
//				return "redirect:/index.jsp?openid=" + openid + "&state="
//						+ randomStr;
//			}
//			userController.doSomeLoginWorkToHomePage(sysUser.getMcid(), map);
			// 登录成功
			return "homePage";
		}
		// 未授权
		return "redirect:" + WeiXinUtil.getStartURLToGetCode();

	}

}
